#include "ecgsignal.h"

EcgSignal::EcgSignal(QObject* parent)
    : QObject { parent }
{
}
EcgSignal& EcgSignal::getInstance()
{
    static EcgSignal instance; // 静态局部变量，确保只初始化一次
    return instance;
}
int EcgSignal::getSignalSize() const
{
    return signalSize;
}

void EcgSignal::setSignalSize(int newSignalSize)
{
    signalSize = newSignalSize;
}

void EcgSignal::readBinaryFile(const QString& filePath)
{
    if (numberChannels > 0) {
        // 释放内存
        for (int i = 0; numberChannels; ++i) {
            data[i].clear();
        }
        data.clear();
    }

    numberChannels = 3; //3导联
    data = QVector<QVector<int16_t>>(numberChannels); //初始化二维数组
    data.squeeze();//释放未使用的容量，将容量调整为实际元素数量。

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        qWarning() << "Failed to open file:" << filePath;
        return;
    }
    QByteArray bytes;
    bytes = file.readAll();
    file.close();

    int size = bytes.size();
    signalSize = size / 6;
    for (int i = 0; i < numberChannels; ++i) {
        //初始化二维数组
        data[i] = QVector<int16_t>(size / 6);
        data[i].squeeze();//释放未使用的容量，将容量调整为实际元素数量。
    }
    int index = 0;
    int index1 = 0;
    for (int i = 0; i < size; i += 2) {
        int16_t value = (static_cast<uint8_t>(bytes.at(i + 1)) << 0) | (static_cast<uint8_t>(bytes.at(i)) << 8);
        data[index][index1] = value;
        if (index == 2) {
            index1++;
        }
        index = (index + 1) % 3;
    }
    qDebug() << "心电数据读取完成";
}
/**
 * @brief EcgSignal::getEcgSignalFragment获取某一片段的心电信号数据
 * @param start 开始点
 * @param duration 持续时间毫秒
 * @return
 */
QVector<QVector<int16_t>> EcgSignal::getEcgSignalFragment(int start, int duration)
{
    if (start < 0) {
        start = 0;
    }
    if (start > signalSize - 1) {
        start = signalSize - 1;
    }
    int count =  duration * ecg.sampleRate() / 1000;
    // qDebug() << "start:" << start;
    // qDebug() << "end:" << end;
    if (count > signalSize - 1 -start) {
        count = signalSize - 1-start;
    }
    QVector<QVector<int16_t>> arr;
    for (int i = 0; i < numberChannels; ++i) {
        arr.append(data[i].mid(start, count));
    }
    return arr;
}
